<template>
  <view class="relative bg-white order-list flex flex-col h-full">
    <nav-bar color="white" bg-color="black" title="菜品" show-back></nav-bar>
    <u-row gutter="10rpx" :customStyle="rowFillterBar">
      <u-col span="3">
        <uni-data-select
          title="选择菜品类别"
          v-model="filterPam.parentId"
          :localdata="foodTypeList"
          :clear="false"
          @change="changeSelect"
        ></uni-data-select>
      </u-col>
      <u-col span="3">
        <u-search
          shape="square"
          placeholder="请输入菜品名称"
          v-model="filterPam.name"
          search-icon-size="15rpx"
          @search="onSearch"
          @custom="onSearch"
          @clear="onSearch"
        ></u-search>
      </u-col>
      <u-col span="1">
        <u-button type="info" color="lightgrey" @click="resetFilter">重置</u-button>
      </u-col>
      <u-col span="1">
        <u-button type="primary" color="#2f90ff" @click="toTypeManage">类品管理</u-button>
      </u-col>
      <u-col span="1">
        <u-button type="primary" color="orange" @click="addItem">添加菜品</u-button>
      </u-col>
    </u-row>
    <u-row customStyle="flex:1;height:100%;align-items: baseline;">
      <view class="px-12rpx w-full box-border flex flex-col h-full">
        <!-- <zb-table
          :show-header="true"
          :columns="[
            { type: 'selection', fixed: true, width: 50 },
            { name: 'name', label: '名称',fixed:false },
            { name: 'foodTypeName', label: '类别' },
            { name: 'price', label: '类别' },
            { name: 'texture', label: '类别' },
            ]"
          :stripe="true"
          :fit="false"
          show-summary
          sum-text="合计"
          :border="true"
          :data="orderList"
        ></zb-table> -->
        <uni-table :loading="pageStatus.loading" class="table-height" stripe emptyText="暂无更多数据" :border="true">
          <!-- 表头行 -->
          <uni-tr class="thead-tr">
            <!-- <uni-th align="center" class="fixed-left">序号</uni-th> -->
            <uni-th align="center">序号</uni-th>
            <uni-th align="center">名称</uni-th>
            <uni-th align="center">类别</uni-th>
            <uni-th align="center">价格（元）</uni-th>
            <uni-th align="center">辣味</uni-th>
            <uni-th align="center">口感</uni-th>
            <uni-th align="center">口味</uni-th>
            <uni-th align="center">禁忌人群</uni-th>
            <!-- <uni-th align="center">状态</uni-th> -->
            <uni-th align="center">图片</uni-th>
            <uni-th align="center">评分</uni-th>
            <uni-th align="center">操作</uni-th>
            <!-- <uni-th align="center" class="fixed-right thead">操作</uni-th> -->
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in orderList" :key="item.buffetOrderId" class="data-tr">
            <uni-td align="center" >{{ index + 1 }}</uni-td>
            <!-- <view align="center" class="fixed-left"
              ><text>{{ index + 1 }}</text></view
            > -->
            <uni-td align="center">{{ item.name }}</uni-td>
            <uni-td align="center">{{ item.foodTypeName }}</uni-td>
            <uni-td align="center">{{ formatMoney(item.price) }}</uni-td>
            <uni-td align="center">{{ item.spicy || "-" }}</uni-td>
            <uni-td align="center">{{ item.texture || "-" }}</uni-td>
            <uni-td align="center">{{ item.flavor || "-" }}</uni-td>
            <uni-td align="center">{{ splitStrToArray(item.tabooPopulation).join(" / ") || "无" }}</uni-td>
            <!-- <uni-td align="center">{{ "---" }}</uni-td> -->
            <uni-td align="center">
              <!-- @ h-50rpx 需要设置固定高以便表格计算, 防止每行数据高度不一的样式问题 -->
              <view class="flex h-50rpx items-center justify-center">
                <!-- <text v-if="!item.photo">暂无图片</text> -->
                <!-- <u-album :urls="[item.photo]" single-size="50rpx" multiple-size="50rpx" max-count="1"></u-album> -->
                <u-image :src="item.photo" mode="aspectFill" width="50rpx" height="50rpx"></u-image>
              </view>
            </uni-td>
            <uni-td align="center">
              <u-rate
                v-model="item.totalStars"
                inactive-color="lightgray"
                :readonly="true"
                active-color="var(--kui-color-theme)"
              ></u-rate>
            </uni-td>
            <uni-td align="center">
              <!-- <view class="fixed-right tdata"> -->
                <view class="relative form-item-btns flex justify-evenly items-center">
                  <view class="mx-5rpx" v-for="(btn, index) in itemBtns" :key="index">
                    <u-icon
                      :name="btn.icon"
                      :label="btn.name"
                      label-pos="bottom"
                      size="15rpx"
                      :color="btn.color || 'grey'"
                      :label-color="btn.color || 'grey'"
                      @click="btn.onClick(item)"
                    ></u-icon>
                  </view>
                </view>
              <!-- </view> -->
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="pagination-box">
          <uni-pagination
            show-icon
            :page-size="filterPam.size"
            :current="filterPam.current"
            :total="filterPam.total"
            @change="pageChange"
          />
        </view>
      </view>
    </u-row>
  </view>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { foodList, getFoolTypeList, foodDel } from "@/api";
import { formatMoney, loadSysDict, splitStrToArray } from "@/utils/util";
import { onShow } from "@dcloudio/uni-app";

const itemBtns = [
  {
    name: "查看",
    value: "detail",
    icon: "eye",
    onClick: (item: any) => uni.navigateTo({ url: `./details?id=${item.foodTypeId}` }),
  },
  {
    name: "编辑",
    value: "edit",
    icon: "edit-pen",
    onClick: (item: any) => uni.navigateTo({ url: `./addAndEdit?id=${item.foodTypeId}&mode=edit` }),
  },
  // { name: "下架", value: "disable", icon: "shopping-cart", onClick: () => {
  //   uni.showToast({
  //     title: "暂不支持",
  //     icon: "none",
  //   });
  // } },
  {
    name: "删除",
    value: "remove",
    icon: "trash",
    color: "red",
    onClick: (item: any) => {
      uni.showModal({
        title: "提示",
        content: "确定删除该菜品吗？",
        success(res) {
          if (res.confirm) {
            deleteFood(item);
            // console.log(error);
          }
        },
      });
    },
  },
];

const rowFillterBar = `
    padding:8rpx;
    position: sticky;
    top: 10vh;
    background: white;
    z-index: 2;
`;

const pageStatus = reactive({
  loading: false,
});

const filterPam = reactive({
  range: [],
  name: "", // 菜品名称 keyword
  current: 1,
  size: 10,
  total: 0,
  parentId: "", // 菜品类型id （foodTypeId）
});

const onSearch = () => {
  filterPam.current = 1;
  getPageData();
};

const resetFilter = () => {
  filterPam.name = "";
  filterPam.current = 1;
  filterPam.parentId = "";
  getPageData();
};

const orderList = ref([]);

const pageChange = (e) => {
  filterPam.current = e.current;
  getPageData();
};

const getPageData = async () => {
  pageStatus.loading = true;
  try {
    const pam = {
      descs: "create_time",
      dataType: 2,
      typeStatus: 1,
      // parentId: '分类id',
      ...filterPam,
    };
    const { data, success } = await foodList(pam);
    console.log(data);
    if (!success) throw new Error("获取数据失败");
    orderList.value = data.records;
    filterPam.total = data.total;
    pageStatus.loading = false;
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

const addItem = () => {
  uni.navigateTo({
    url: `./addAndEdit?mode=add`,
  });
};

const toTypeManage = () => {
  uni.navigateTo({
    url: "./type-manage",
  });
};

const foodTypeList = ref([]);
const changeSelect = (e) => {
  filterPam.parentId = e;
  getPageData();
};
const getTypeList = async () => {
  try {
    const pam = {
      parentId: 0,
      dataType: 1,
      typeStatus: 1,
    };
    const { data, success } = await getFoolTypeList(pam);
    if (!success) throw new Error("获取数据失败");
    const netData = data.map((v) => ({ ...v, text: v.name, value: v.foodTypeId }));
    foodTypeList.value = [{ text: "全部", value: "" }, ...netData];
    console.log("getTypeList>>", data);
  } catch (error) {
    console.log(error);
  }
};

onMounted(async () => {
  /** 字典 */
  // loadSysDict(["sys_tabooPopulation", "sys_flavor", "sys_texture", "sys_texture", "sys_spicy"]);
  // const dicts = reactive();
  /** 获取菜品分类列表 */
  getTypeList();
  getPageData();
});

onShow(() => {

  // 从其他页面返回时，重新获取数据 (? 这里只考虑有数据的情况刷新)
  if (orderList.value.length > 0) {
    // 重置分页
    filterPam.current = 1;
    // 刷新
    getPageData();
  }

});

// 删除菜品
const deleteFood = async (item) => {
  try {
    const pam = { ids: item.foodTypeId };
    const { data, success } = await foodDel(pam);
    if (!success) throw new Error("删除失败");
    uni.showToast({ title: "删除成功" });
    getPageData();
  } catch (error) {
    console.log(error);
    uni.showToast({ title: "删除失败", icon: "fail" });
  }
};
</script>
<style lang="scss" scoped>
.order-list {
  ::v-deep .u-search__content {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
    margin-right: -10px;
    height: 25rpx;

    // .u-search__content__icon {
    //   display: none;
    // }

    .uni-input-input {
      height: 25rpx;
    }
  }
  ::v-deep .u-search__action {
    background: var(--kui-color-theme);
    max-height: 25rpx;
    height: 25rpx;
    border-radius: 3rpx;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 5rpx;
    font-size: 10rpx;
  }

  ::v-deep .u-button {
    border-radius: 3rpx;
    height: 25rpx;
  }
}

.fixed-left {
  position: sticky;
  background-color: white;
  left: 0;
  height: 100%;
  display: flex;
  text-align: center;
  justify-content: center;
  align-items: center;
  // position: absolute;
}

.fixed-right {
  // display: flex;
  // flex-direction: row;
  position: sticky;
  right: 0;
  background-color: white;
  height: max-content;
  box-sizing: border-box;
  display: table-cell;

  &.thead {
    display: block;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }

  &.tdata {
    background-color: white;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }
  ::v-deep .u-button {
    margin-right: 5rpx;
    height: 20rpx;
  }
}

.form-item-btns {
  // position: relative;
  display: flex;
  flex-direction: row;
  float: right;

}

.thead-tr {
  position: sticky;
  top: 0;
  white-space: nowrap;
  z-index: 1;
}

.data-tr {
  overflow: auto;
  position: relative;
  // z-index: 1;
}

.table-height {
  // max-height: 70vh;
  flex: auto;

  ::v-deep &.uni-table-scroll {
    border: 1px #ebeef5 solid;
  }
}

.pagination-box {
  padding: 10rpx;
  display: flex;
  flex-direction: row;
  justify-content: right;
  position: sticky;
  bottom: 0;
  background: white;
}
</style>
